﻿
public class NetHandler_FetchCandidates : GameServerMessageHandler
{
    public const string Key = "FetchCandidates";

    public static NetHandler_FetchCandidates NewHandler()
    {
        return new NetHandler_FetchCandidates();
    }

    protected override ISerialize NewData() => new FetchCandidatesRequestData();

    public override void _Execute(TCPClient client, ISerialize _data)
    {
        FetchCandidatesRequestData requestData = _data as FetchCandidatesRequestData;

        GameDebug.Log($"用户{client.userID} 获取嘉宾:{requestData?.num}");

        UserServer user = Game.instance.GetUser(client.userID);

        FetchCandidatesResponseData response = new FetchCandidatesResponseData();

        if (user == null)
        {
            GameDebug.LogError($"找不到用户：{client.userID}");
            response.code = ErrorCode.UserNotFound;
        }
        else
        {
            if (requestData != null)
            {
                List <UserMomentsInfo> candidates = new List<UserMomentsInfo>();

                int userGender = user.data.userInfo.gender;
                int fetchGender = userGender == Gender.man ? Gender.woman : Gender.man;
                UserTable[] usersList = UserServer.FindInUsersTable(fetchGender, user.data.userInfo.locationCity,
                  user.data.userInfo.hometownProvince, user.data.userInfo.hometownCity,user.data.requirement,requestData.num);

                if(usersList.Length != requestData.num)
                {
                    GameDebug.LogError($"usersList.Length ：{usersList.Length}  != requestData.num:{requestData.num}");
                }

                for (int i = 0; i < usersList.Length; i++)
                {
                    if (usersList[i] == null)
                        continue;

                    UserMomentsInfo newUserMomentsInfo = new UserMomentsInfo();

                    long deviceId = users.UserTableId2DeviceId(usersList[i].dbId, usersList[i].user.id);
                    User gameUser = UserServer.UserTable2User(deviceId, usersList[i].user);
                   
                    UserInfo newUserInfo = gameUser.userInfo;

                    newUserMomentsInfo.user = newUserInfo;
                    newUserMomentsInfo.moments = gameUser.moments.Map(e=>new UserMoment(newUserInfo,e)).AsArray();
                    candidates.Add(newUserMomentsInfo);
                }
                response.candidates = candidates;

                response.code = 0;
            }
            else
            {
                GameDebug.LogError($"requestData == null _data:{_data != null} type:{_data.GetType()}");
                response.code = -1;
            }
        }

        byte[] data = response.Write();
        this.SendResponse(client, Key, this.m_MessageReceived.seq, data);
    }
}
